package com.rabbiter.oes.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rabbiter.oes.entity.Major;
import com.rabbiter.oes.result.R;
import com.rabbiter.oes.service.impl.MajorServiceImpl;
import com.rabbiter.oes.vo.MajorVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "专业")
@RestController
public class MajorController {

    @Autowired
    private MajorServiceImpl majorService;

    @ApiOperation(value = "分页查询专业信息", notes = "分页查询专业信息", httpMethod = "GET")
    @GetMapping("/majors/{page}/{size}/{name}")
    public R<IPage<MajorVO>> findPage(@PathVariable Integer page, @PathVariable("size") Integer size, @PathVariable("name") String name) {
        Page<MajorVO> majorPage = new Page<>(page, size);
        IPage<MajorVO> majorIPage = majorService.findPage(majorPage, name);
        return R.<IPage<MajorVO>>ok("分页查询专业信息").data(majorIPage);
    }

    @ApiOperation(value = "查询全部专业信息", notes = "查询全部专业信息", httpMethod = "GET")
    @GetMapping("/majorFindAll")
    public R<List<Major>> findAll() {
        List<Major> majors = majorService.findAll();
        return R.<List<Major>>ok("分页查询专业信息").data(majors);
    }

    @ApiOperation(value = "根据id查询专业信息", notes = "根据id查询专业信息", httpMethod = "GET")
    @GetMapping("/major/{id}")
    public R<Major> findById(@PathVariable("id") Integer id) {
        Major major = majorService.findById(id);
        return R.<Major>ok().data(major);
    }

    @ApiOperation(value = "根据id删除专业信息", notes = "根据id删除专业信息", httpMethod = "DELETE")
    @DeleteMapping("/major/{id}")
    public R deleteById(@PathVariable("id") Integer id) {
        majorService.deleteById(id);
        return R.ok("删除成功");
    }

    @ApiOperation(value = "修改专业信息", notes = "修改专业信息", httpMethod = "PUT")
    @PutMapping("/major")
    public R update(@RequestBody Major major) {
        String name = major.getName();
        Long countByName = majorService.findCountByName(name);
        if (countByName == 0) {
            majorService.update(major);
            return R.ok().data(true);
        } else {
            return R.ok("专业已存在！").data(false);
        }
    }

    @ApiOperation(value = "添加专业信息", notes = "添加专业信息", httpMethod = "POST")
    @PostMapping("/major")
    public R add(@RequestBody Major major) {
        String name = major.getName();
        Long countByName = majorService.findCountByName(name);
        if (countByName == 0) {
            majorService.add(major);
            return R.ok().data(true);
        } else {
            return R.ok("专业已存在！").data(false);
        }
    }

}
